import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 666
 * Date: 2023-04-13
 * Time: 10:17
 */
public class TcpEcoserver {
 ServerSocket serverSocket = null;
    Map<String, String> map = new HashMap<>();
    public TcpEcoserver(int port) throws IOException {
        map.put("cat","猫");
        map.put("bit","比特");
        map.put("go","狗");
        map.put("sb","傻比");
        serverSocket = new ServerSocket(port);
    }
    public void  start() throws IOException {
        System.out.println("服务器启动->");

        while(true){
         Socket  socket =   serverSocket.accept();
            processClient(socket);
        }

    }

    private void processClient(Socket clientSocket) throws IOException {
        System.out.println("客户端上线");
    try (InputStream inputStream = clientSocket.getInputStream();
         OutputStream outputStream = clientSocket.getOutputStream()){
        Scanner scanner =new Scanner(inputStream);
        PrintWriter printWriter = new PrintWriter(outputStream);
        while (true){

            if(!scanner.hasNext()){
                System.out.println("客户端下线");
                break;
            }
            String request = scanner.next();
            String response = process(request);
            printWriter.println(response);
            printWriter.flush();
            System.out.println("请求为"+request+"响应为"+response);
        }
    } catch (IOException e) {
       e.printStackTrace();
    }
    finally {
        clientSocket.close();
    }

    }

    public String process(String request) {

        return map.getOrDefault(request,"没找到");
    }

    public static void main(String[] args) throws IOException {
        TcpEcoserver tcpEcoserver = new TcpEcoserver(9000);
        tcpEcoserver.start();
    }
}
